package com.goalias.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TimeGlobalFilter implements GlobalFilter,Ordered{
    Logger logger = LoggerFactory.getLogger(TimeGlobalFilter.class);

    public static final String REQUEST_TIME_BEGIN = "requestTimeBegin";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("进入全局接口耗时分析器");
        exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if (startTime != null) {
                        logger.info("访问接口主机：{}:{}" , exchange.getRequest().getURI().getHost(), exchange.getRequest().getURI().getPort());
                        logger.info("访问接口URL：{}?{}", exchange.getRequest().getPath(),exchange.getRequest().getURI().getRawQuery());
                        logger.info("访问接口耗时：{}", (System.currentTimeMillis() - startTime)+"毫秒");
                    }
                })
        );
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
